package com.le.tester.book.concurrentchallenge.cancelclose;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;

/**
 * createTime：2025-04-08 10:12
 * description：比较可靠的日志服务
 */
public class LogService {

    private final BlockingQueue<String> blockingQueue;

    private final LoggerThread loggerThread;

    private final PrintWriter write;

    private boolean isShutdown;

    private int reservations;

    public LogService(BlockingQueue<String> blockingQueue, LoggerThread loggerThread, PrintWriter write, boolean isShutdown, int reservations) {
        this.blockingQueue = blockingQueue;
        this.loggerThread = loggerThread;
        this.write = write;
        this.isShutdown = isShutdown;
        this.reservations = reservations;
    }

    public void start() {
        loggerThread.start();
    }

    public void stop() {
        synchronized (this) {
            isShutdown = true;
        }
        loggerThread.interrupt();
    }

    public void log(String msg) throws InterruptedException {
        synchronized (this) {
            if (isShutdown) {
                throw new IllegalStateException();
            }
            ++reservations;
        }
        blockingQueue.put(msg);
    }

    private class LoggerThread extends Thread {

        public void run() {
            while (true) {
                try {
                    synchronized (LogService.class) {
                        if (isShutdown && reservations == 0) {
                            break;
                        }
                    }
                    String msg = blockingQueue.take();
                    synchronized (LogService.class) {
                        --reservations;
                    }
                } catch (InterruptedException ignore) {

                }
            }
        }
    }
}

